package com.zj.auth.service;

import com.zj.auth.LoginCallBack;
import com.zj.auth.bean.LoginToInterface;
import com.zj.auth.bean.LoginToken;
import com.zj.auth.cache.RedisUtil;
import com.zj.auth.config.AuthConfig;
import com.zj.auth.domain.Customer;
import cn.zj.smart.util.StringUtil;
import cn.zj.smart.util.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

/**
 * 统一的登录逻辑
 * @author xi.yang
 * @create 2020-11-19 19:53
 **/
@Component
@EnableConfigurationProperties(AuthConfig.class)
public class AuthImpl implements AuthInterface,LoginAuth {
    @Autowired
    private AuthConfig authConfig;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private LoginCallBack loginCallBack;

    /**
     * 统一登陆入口
     * @param loginToInterface
     * @return
     */
    @Override
    public LoginToken login(LoginToInterface loginToInterface) {
        // 转换登陆对象
        initLoginTo(loginToInterface);
        // 验证数据
        validate();
        // 获取用户信息
        Customer customer = getCustomer();
        if (null == customer) {
            // 注册新用户
            customer = registerCustomer();
            loginCallBack.createNewCustomerSuccess(customer.getId());
        }
        final String token = StringUtil.getUUID();
        redisUtil.cacheCustomerToken(customer.getId(), token);
        loginCallBack.loginSuccess(customer.getId());
        return LoginToken.builder()
                .customerId(customer.getId())
                .tokenHeader(authConfig.getTokenHeaderName())
                .expire(LocalDateTime.now().plus(authConfig.getTokenRedisExpire() - 1, ChronoUnit.MINUTES).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli())
                .token(token)
                .build();
    }

    @Override
    public void initLoginTo(LoginToInterface loginToInterface) {
        throw new ServiceException("initLoginTo");
    }

    @Override
    public void validate() {
        throw new ServiceException("validate");
    }

    @Override
    public Customer getCustomer() {
        throw new ServiceException("getCustomer");
    }

    @Override
    public Customer registerCustomer() {
        throw new ServiceException("registerCustomer");
    }
}
